<template>
  <div class="profile-container">
    <a-row :gutter="24">
      <!-- 用户信息卡片 -->
      <a-col :span="8">
        <a-card :bordered="false">
          <template #cover>
            <div class="profile-cover">
              <div class="profile-avatar">
                <a-avatar :size="104" :src="getAvatarUrl(userInfo.avatar)" />
              </div>
            </div>
          </template>
          <template #title>个人信息</template>
          
          <div class="profile-info">
            <div class="info-item">
              <div class="info-label">用户名</div>
              <div class="info-value">{{ userInfo.username }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">昵称</div>
              <div class="info-value">{{ userInfo.nickname }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">邮箱</div>
              <div class="info-value">{{ userInfo.email || '未设置' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">手机号</div>
              <div class="info-value">{{ userInfo.phonenumber || '未设置' }}</div>
            </div>
          </div>
          
          <template #actions>
            <a-button type="primary" block @click="handleEditBasic">
              修改基本信息
            </a-button>
          </template>
        </a-card>
      </a-col>
      
      <!-- 详细信息标签页 -->
      <a-col :span="16">
        <a-card :bordered="false">
          <a-tabs v-model:activeKey="activeTab">
            <!-- 基本信息标签 -->
            <a-tab-pane key="basic" tab="基本信息">
              <a-form :model="basicForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-form-item label="用户名">
                  <a-input v-model:value="basicForm.userName" disabled />
                </a-form-item>
                <a-form-item label="昵称">
                  <a-input v-model:value="basicForm.nickName" placeholder="请输入昵称" />
                </a-form-item>
                <a-form-item label="性别">
                  <a-radio-group v-model:value="basicForm.sex">
                    <a-radio :value="0">男</a-radio>
                    <a-radio :value="1">女</a-radio>
                    <a-radio :value="2">未知</a-radio>
                  </a-radio-group>
                </a-form-item>
                <a-form-item label="邮箱">
                  <a-input v-model:value="basicForm.email" placeholder="请输入邮箱" />
                </a-form-item>
                <a-form-item label="手机号">
                  <a-input v-model:value="basicForm.phonenumber" placeholder="请输入手机号" />
                </a-form-item>
                <a-form-item label="个人简介">
                  <a-textarea v-model:value="basicForm.remark" placeholder="请输入个人简介" :rows="4" />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 18, offset: 6 }">
                  <a-button type="primary" @click="saveBasicInfo" :loading="loading">保存</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
            
            <!-- 修改密码标签 -->
            <a-tab-pane key="password" tab="修改密码">
              <a-form :model="passwordForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-form-item label="原密码">
                  <a-input-password v-model:value="passwordForm.oldPassword" placeholder="请输入原密码" />
                </a-form-item>
                <a-form-item label="新密码">
                  <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" />
                </a-form-item>
                <a-form-item label="确认密码">
                  <a-input-password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 18, offset: 6 }">
                  <a-button type="primary" @click="changePassword" :loading="loading">保存</a-button>
                </a-form-item>
              </a-form>
            </a-tab-pane>
            
            <!-- 修改头像标签 -->
            <a-tab-pane key="avatar" tab="修改头像">
              <div class="avatar-upload">
                <div class="avatar-preview">
                  <a-avatar :size="128" :src="getAvatarUrl(avatarUrl || userInfo.avatar)" />
                </div>
                <div class="avatar-actions">
                  <a-upload
                    name="avatar"
                    list-type="picture-card"
                    :show-upload-list="false"
                    :before-upload="beforeAvatarUpload"
                    :custom-request="handleAvatarChange"
                    accept="image/jpeg,image/jpg,image/png,image/gif,image/bmp,image/webp"
                    :max-count="1"
                  >
                    <div>
                      <plus-outlined />
                      <div style="margin-top: 8px">上传头像</div>
                    </div>
                  </a-upload>
                  <p class="upload-tip">支持JPG、PNG、GIF、BMP、WEBP格式，大小不超过2MB</p>
                  <a-button type="primary" @click="saveAvatar" :disabled="!avatarUrl" :loading="loading">保存头像</a-button>
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { useAuthStore } from '@/stores/auth'
import * as userApi from '@/api/user'
import type { SysUser } from '@/types/user'

const authStore = useAuthStore()

// 用户详细信息
const userDetail = ref<SysUser | null>(null)
const loading = ref(false)

// 用户信息（优先使用详情，否则使用store中的基本信息）
const userInfo = computed(() => {
  if (userDetail.value) {
    return {
      userId: userDetail.value.userId,
      username: userDetail.value.userName,
      nickname: userDetail.value.nickName,
      avatar: userDetail.value.avatar,
      email: userDetail.value.email,
      phonenumber: userDetail.value.phonenumber
    }
  }
  return authStore.userInfo
})

// 当前激活标签
const activeTab = ref('basic')

// 基本信息表单
const basicForm = reactive({
  userName: '',
  nickName: '',
  sex: 0,
  email: '',
  phonenumber: '',
  remark: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 头像上传相关
const avatarUrl = ref('')

// 获取完整的头像URL（通过nginx代理）
const getAvatarUrl = (url: string | undefined) => {
  if (!url) {
    return ''
  }
  // 如果已经是完整URL（包含http://或https://），直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  // 如果是相对路径，拼接nginx地址
  if (url.startsWith('/')) {
    return 'http://127.0.0.1:80' + url
  }
  return url
}

// 加载用户详情
const loadUserDetail = async () => {
  loading.value = true
  try {
    const res = await userApi.getProfile()
    if (res) {
      userDetail.value = res
      // 更新表单数据
      basicForm.userName = res.userName || ''
      basicForm.nickName = res.nickName || ''
      basicForm.sex = res.sex ?? 0
      basicForm.email = res.email || ''
      basicForm.phonenumber = res.phonenumber || ''
      basicForm.remark = res.remark || ''
    }
  } catch (error) {
    console.error('获取用户详情失败:', error)
    message.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载用户详情
onMounted(() => {
  loadUserDetail()
})

// 编辑基本信息
const handleEditBasic = () => {
  activeTab.value = 'basic'
}

// 保存基本信息
const saveBasicInfo = async () => {
  try {
    loading.value = true
    await userApi.updateProfile({
      nickName: basicForm.nickName,
      sex: basicForm.sex,
      email: basicForm.email,
      phonenumber: basicForm.phonenumber,
      remark: basicForm.remark
    })
    
    message.success('保存成功')
    // 重新加载用户详情
    await loadUserDetail()
    // 更新store中的用户信息
    if (userDetail.value) {
      authStore.setUserInfo({
        userId: userDetail.value.userId,
        username: userDetail.value.userName,
        nickname: userDetail.value.nickName,
        avatar: userDetail.value.avatar,
        email: userDetail.value.email,
        phonenumber: userDetail.value.phonenumber
      })
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    message.error('保存失败')
  } finally {
    loading.value = false
  }
}

// 修改密码
const changePassword = async () => {
  if (!passwordForm.oldPassword) {
    message.error('请输入原密码')
    return
  }
  
  if (!passwordForm.newPassword) {
    message.error('请输入新密码')
    return
  }
  
  if (passwordForm.newPassword.length < 6) {
    message.error('新密码长度不能少于6位')
    return
  }
  
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    message.error('两次输入的密码不一致')
    return
  }
  
  try {
    loading.value = true
    await userApi.updatePassword(passwordForm.oldPassword, passwordForm.newPassword)
    message.success('密码修改成功')
    // 清空表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    console.error('修改密码失败:', error)
    message.error('修改密码失败')
  } finally {
    loading.value = false
  }
}

// 头像上传前检查
const beforeAvatarUpload = (file: File) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp' || file.type === 'image/webp'
  if (!isJpgOrPng) {
    message.error('只能上传JPG、PNG、GIF、BMP、WEBP格式的图片!')
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片必须小于2MB!')
    return false
  }
  
  return true
}

// 头像变更 - 手动上传
const handleAvatarChange = async (options: any) => {
  const { file } = options
  
  try {
    loading.value = true
    // 调用上传接口
    const uploadedUrl = await userApi.uploadAvatar(file)
    if (uploadedUrl) {
      // 保存原始URL（相对路径），用于后续保存到数据库
      avatarUrl.value = uploadedUrl
      // 标记上传成功
      options.onSuccess(uploadedUrl, file)
      message.success('头像上传成功，请点击保存按钮保存')
    }
  } catch (error: any) {
    console.error('头像上传失败:', error)
    message.error(error?.message || '头像上传失败')
    // 标记上传失败
    options.onError(error)
  } finally {
    loading.value = false
  }
}

// 保存头像
const saveAvatar = async () => {
  if (!avatarUrl.value) {
    message.warning('请先上传头像')
    return
  }
  
  try {
    loading.value = true
    await userApi.updateAvatar(avatarUrl.value)
    message.success('头像保存成功')
    // 重新加载用户详情
    await loadUserDetail()
    // 更新store中的用户信息
    if (userDetail.value) {
      authStore.setUserInfo({
        userId: userDetail.value.userId,
        username: userDetail.value.userName,
        nickname: userDetail.value.nickName,
        avatar: userDetail.value.avatar,
        email: userDetail.value.email,
        phonenumber: userDetail.value.phonenumber
      })
    }
    avatarUrl.value = ''
  } catch (error: any) {
    console.error('保存头像失败:', error)
    message.error(error?.message || '保存头像失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.profile-container {
  padding: 24px;
}

.profile-cover {
  height: 120px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 40px;
}

.profile-avatar {
  margin-bottom: -40px;
}

.profile-info {
  margin-top: 20px;
}

.info-item {
  display: flex;
  margin-bottom: 16px;
}

.info-label {
  width: 70px;
  color: rgba(0, 0, 0, 0.45);
}

.info-value {
  flex: 1;
  color: rgba(0, 0, 0, 0.85);
}

.avatar-upload {
  display: flex;
  padding: 24px;
  gap: 48px;
}

.avatar-preview {
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.upload-tip {
  color: rgba(0, 0, 0, 0.45);
  margin-top: 8px;
}
</style>
